package com.wxt.eventbusanalysis.annotationTest.api;

import android.util.Log;

import com.wxt.eventbusanalysis.annotationTest.annotations.ReqParam;
import com.wxt.eventbusanalysis.annotationTest.annotations.ReqType;
import com.wxt.eventbusanalysis.annotationTest.annotations.ReqUrl;
import com.wxt.eventbusanalysis.annotationTest.interfaces.IReqApi;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

/**
 * @author wuxiaotao on 2017/7/3.
 */

public class MyApi {

    public String testApi() {
        IReqApi api = create(IReqApi.class);
        return api.getNetTime("测试");
    }

    private <T> T create(final Class<T> mApi) {
        return (T) Proxy.newProxyInstance(mApi.getClassLoader(), new Class[]{mApi}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                ReqType reqType = method.getAnnotation(ReqType.class);
                Log.e("WXT", "====请求类型===" + (reqType.reqType() == ReqType.ReqTypeEnum.POST ? "POST" : "OTHER"));
                ReqUrl reqUrl = method.getAnnotation(ReqUrl.class);
                Log.e("WXT", "====请求URL===" + reqUrl.value());

                Annotation[][] params = method.getParameterAnnotations();//拿到参数注解
                for (int i = 0; i < params.length; i++) {
                    Annotation[] annotations = params[i];
                    if (annotations != null) {
                        ReqParam reqParam = (ReqParam) annotations[0];
                        Log.e("WXT", "====请求参数===" + reqParam.value() + "==" + args[i]);
                    }
                }

                String value = "http://"+ reqUrl.value();
                URL url = null;
                try {
                    url = new URL(value);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                URLConnection uc = null;
                try {
                    uc = url.openConnection();
                    uc.connect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return new Date(uc.getDate()).toString();
            }
        });
    }
}
